package com.hut.oa.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录拦截
 * @author 朱嘉茵
 *
 */
public class LoginInterceptor implements HandlerInterceptor {
	Logger log=LoggerFactory.getLogger(getClass());

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpSession session=request.getSession();
		if(session.getAttribute("userinfo")==null){
			log.info("进入登录过滤器,未登录");
			if(isAjax(request)){
				response.setStatus(402);//ajax请求直接返回错误码
			}else{
				response.sendRedirect("/oa/login");
			}
			return false;
		}
		//获取当前路径
		String requestURI=request.getRequestURI();//获取相对路径
		String queryString=request.getQueryString();//获取参数
		if(queryString!=null){
			String[] stringArr=queryString.split("&");
			for (int i = 0; i < stringArr.length; i++) {
				if(stringArr[i].startsWith("page") || stringArr[i].startsWith("sort")){//去掉分页的参数
					queryString=queryString.replaceAll("&"+stringArr[i], "");
				}
			}
			requestURI+="?"+queryString;
		}
		log.info("当前路径： {}",requestURI);
		request.setAttribute("requestURI", requestURI);
		//阻止从浏览器地址输入地址进入
		//System.out.println(request.getHeader("referer"));
		/*if(!"http://localhost:8080/oa/main".equals(request.getHeader("referer")) && !"http://localhost:8080/oa/login".equals(request.getHeader("referer"))){
			log.info("浏览器输入错误路径： {}",request.getHeader("referer"));
			response.sendRedirect("/oa/main");
			return false;
		}*/
		return true;
	}
	/**
	 * 过滤ajax请求
	 * @param request
	 * @return
	 */
	private boolean isAjax(HttpServletRequest request) {
		return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
	}

}
